#!/usr/bin/python
'''
主要用来生成SUMMARY。

bug:生成目录文件实现的有问题。
'''
from os import listdir, path
import re

max_depth = 5
excludes = ['引用', '目录.md', 'SUMMARY.md', 'update_index.py', 'interview', 'README.md']
indent_space = '    '

def IsExclude(file_name: str, is_file=True):
    # 排除指定的文件
    for exclude_item in excludes:
        if len(re.findall(exclude_item, file_name)) > 0:
            return True

    # 排除非md后缀的文件
    if is_file:
        arr = file_name.split(".")
        if len(arr) >= 1 and arr[len(arr) - 1] != 'md':
            return True

    return False

def UpdateIndexInner(dir, index_file, depth=0):
    if depth == max_depth:
        return

    curr_files = []
    curr_sub_dirs = []

    dir_entrys = listdir(dir)
    for dir_entry in dir_entrys:
        if path.isfile(path.join(dir,dir_entry)):
            if not IsExclude(dir_entry):
                curr_files.append(dir_entry)
        else:
            if not IsExclude(dir_entry):
                curr_sub_dirs.append(dir_entry)
    if depth == 0 or depth == 1:
        module_name = ''
        module_name_prefix = '## '
        module_name_subfix = '模块'
        if path.basename(dir) == '.':
            module_name = module_name_prefix + 'normal' + module_name_subfix
        else:
            module_name = module_name_prefix + path.basename(dir) + module_name_subfix
        index_file.write(module_name)
        index_file.write('\n')
    
    index_item_template = '- [${index_name}](${index_url})'
    for file_item in curr_files:
        file_name, file_subfix = file_item.split('.')
        index_item = index_item_template.replace('${index_name}', file_name)\
            .replace('${index_url}', dir + '/' + file_item)
        index_file.write(index_item)
        index_file.write('\n')
    

    for sub_dir in curr_sub_dirs:
        UpdateIndexInner(dir + "/" + sub_dir, index_file, depth+1)

def UpdateSummaryInner(dir, index_file, depth=0):
    if depth == max_depth:
        return
    curr_files = []
    curr_sub_dirs = []

    dir_entrys = listdir(dir)
    for dir_entry in dir_entrys:
        if path.isfile(path.join(dir,dir_entry)):
            if not IsExclude(dir_entry):
                curr_files.append(dir_entry)
        elif not IsExclude(dir_entry, False):
            curr_sub_dirs.append(dir_entry)

    # write parent title
    if len(curr_files) > 0 and dir.strip() != '.':
        parent_title_indent_space = indent_space * (depth - 1)
        name = dir.split('/')[-1:][0]
        parent_link_file = dir + '/README.md'
        if not path.exists(path.join(dir, 'README.md')):
            t = open(parent_link_file, 'w')
            t.write(name)
            t.close()
        parent_title =  parent_title_indent_space + '- [%s](%s)' % (name, parent_link_file)
        index_file.write(parent_title)
        index_file.write('\n')

    # write child title
    sub_title_indent_space = indent_space * (depth)
    index_item_template = sub_title_indent_space + '- [${index_name}](${index_url})'
    curr_files.sort()
    for file_item in curr_files:
        file_name, file_subfix = file_item.split('.')
        index_item = index_item_template.replace('${index_name}', file_name)\
            .replace('${index_url}', dir + '/' + file_item)
        index_file.write(index_item)
        index_file.write('\n')
    
    curr_sub_dirs.sort()
    for sub_dir in curr_sub_dirs:
        UpdateSummaryInner(dir + "/" + sub_dir, index_file, depth+1)

# 目前只支持一层子目录
def UpdateIndex(dir, index_file_name):
    index_file = open(index_file_name, 'w')
    UpdateIndexInner(dir, index_file)
    index_file.close()

def UpdateSummary(dir, summary_file_name):
    summary_file = open(summary_file_name, 'w')
    top_str = '''# Summary\n[目录](./目录.md)\n'''
    summary_file.write(top_str)
    UpdateSummaryInner(dir, summary_file)
    summary_file.close()

if __name__ == '__main__':
    UpdateIndex(".", "目录.md")
    UpdateSummary(".", 'SUMMARY.md')